package de.koller.aframe.util.resource;

import de.koller.aframe.plain.Sprite;
import de.koller.oceanFramework.OceanException;
import java.awt.GraphicsConfiguration;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

public class SpriteTileGen {
	
	private final GraphicsConfiguration graphicsConfiguration;
	private BufferedImage tilemap;
	private File tileConfig;
	
	private final Map<String, Sprite> tiles = new HashMap<>();
	
	
	private SpriteTileGen( String tileMap, String tileConfig, GraphicsConfiguration gc ) {
		this.graphicsConfiguration = gc;
		this.tilemap = IOLoader.loadLocalImage( tileMap );
		this.tileConfig = new File( tileConfig );
		
		try {
			loadTiles();
		} catch( IOException ex ) {
			throw new OceanException( ex );
		}
	}
	
	/** tileconfig format: T [subX] [suby] [subw] [subh] [transparency] [name]
	 *  [transparency] O: undurchsichtig, T: transparent B: bitmask */
	public static SpriteTileGen create( String tileMap, String tileConfig, GraphicsConfiguration gc ) {
		return new SpriteTileGen( tileMap, tileConfig, gc );
	}
	
	private void loadTiles() throws IOException {
		BufferedReader o = new BufferedReader( new InputStreamReader( new FileInputStream( tileConfig ) ) );

		String s;
		while( (s = o.readLine()) != null ) {
			if( s.startsWith( "//" ) ) continue;
			
			if( s.startsWith( "T" ) ) {
				StringTokenizer st = new StringTokenizer( s );
				st.nextToken();
				int sx = Integer.parseInt( st.nextToken() );
				int sy = Integer.parseInt( st.nextToken() );
				int sw = Integer.parseInt( st.nextToken() );
				int sh = Integer.parseInt( st.nextToken() );
				String t = st.nextToken();
				String n = st.nextToken();
				
				createTile( sx, sy, sw, sh, t, n );
			}
		}
		
	}
	
	private void createTile( int sx, int sy, int sw, int sh, String transparency, String name ) {
		int t = -1;
		if( transparency.equals( "O" ) ) t = Transparency.OPAQUE;
		if( transparency.equals( "T" ) ) t = Transparency.TRANSLUCENT;
		if( transparency.equals( "B" ) ) t = Transparency.BITMASK;
		
		BufferedImage img = graphicsConfiguration.createCompatibleImage( sw, sh, t );
		Sprite s = new Sprite( img );
		
		for( int x = 0; x < s.width; x++ )
			for( int y = 0; y < s.height; y++ )
				s.raster.setPixel( tilemap.getRGB( sx+x, sy+y ), x, y );
		tiles.put( name, s );
	}
	
	public Sprite getSprite( String name ) {
		Sprite s = tiles.get( name );
		if( s == null )
			throw new OceanException( name + " is not defined as tile" );
		return s;
	}
	
}
